import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import {
  getDevelopList,
  deleteDevelop,
  addDevelop,
  editDevelops
} from "@/api/develops";
import { usePublicHooks } from "./system";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import { type FormItemProps } from "./types";
import { cloneDeep, isAllEmpty } from "@pureadmin/utils";
import { type PaginationProps } from "@pureadmin/table";

export function useDept() {
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    searchText: "",
    searchType: ""
  });
  const form = reactive({
    name: "",
    status: "",
    onePage: pagination
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const { tagStyle } = usePublicHooks();
  const changeStatus = value => {
    form.status = value;
  };
  const time = ref();
  time.value = dayjs(new Date()).format("YYYY-MM-DD hh:mm:ss");
  const columns: TableColumnList = [
    {
      label: "用户编号",
      prop: "id",
      width: 180,
      align: "left"
    },
    {
      label: "用户名称",
      prop: "userAccount",
      minWidth: 70
    },
    {
      label: "用户昵称",
      prop: "userNiCheng",
      minWidth: 70
    },

    {
      label: "部门",
      prop: "userDep",
      minWidth: 70
    },
    {
      label: "状态",
      prop: "userState",
      minWidth: 200,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.userState)}>
          {row.userState === 1 ? "启用" : "停用"}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      minWidth: 200,
      prop: "addTime"
    },
    {
      label: "操作",
      fixed: "right",
      width: 160,
      slot: "operation"
    }
  ];

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const Result = await getDevelopList(pagination);
    dataList.value = Result.result;
    pagination.total = Result.onePage.total;
    pagination.pageSize = Result.onePage.pageSize;
    pagination.currentPage = Result.onePage.currentPage;
    if (!isAllEmpty(form.name)) {
      dataList.value = Result.result.filter(
        item => item.userAccount == form.name
      );
      pagination.total = dataList.value.length;
    }
    if (!isAllEmpty(form.status)) {
      dataList.value = Result.result.filter(
        item => item.userState == form.status
      );
      pagination.total = dataList.value.length;
    }
    if (!isAllEmpty(form.name) && !isAllEmpty(form.status)) {
      dataList.value = Result.result
        .filter(item => item.userAccount == form.name)
        .filter(item => item.userState == form.status);
      pagination.total = dataList.value.length;
    }
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  function formatHigherDeptOptions(treeList) {
    // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = treeList[i].status === 0 ? true : false;
      formatHigherDeptOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}开发人员`,
      props: {
        formInline: {
          higherDeptOptions: formatHigherDeptOptions(cloneDeep(dataList.value)),
          userAccount: row?.userAccount,
          userNiCheng: row?.userNiCheng,
          userDep: row?.userDep,
          userState: row?.userState ?? 0,
          id: row?.id,
          addTime: time
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了名称为${curData.userNiCheng}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (title == "编辑" && row.userState != curData.userState) {
            const rsID = {
              rsID: curData.id
            };
            const res = await editDevelops(rsID);
            if (res.isSuccess == true) {
              chores();
              onSearch(); // 刷新表格数据
            } else {
              message("编辑失败", { type: "error" });
            }
          } else {
            done();
          }
          if (valid && title == "新增") {
            const res = await addDevelop(curData);
            if (res.isSuccess == true) {
              chores();
              onSearch(); // 刷新表格数据
            } else {
              message("新增失败", { type: "error" });
            }
          }
        });
      }
    });
  }

  async function handleDelete(row) {
    const rsID = {
      rsID: row.id
    };
    const res = await deleteDevelop(rsID);
    if (res.isSuccess == true) {
      message(`您删除了为${row.id}的这条数据`, { type: "success" });
      onSearch();
    }
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    pagination,
    columns,
    dataList,
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、编辑部门 */
    openDialog,
    /** 删除部门 */
    handleDelete,
    handleSelectionChange,
    changeStatus,
    //addNewDelp
    handleSizeChange,
    handleCurrentChange
  };
}
